package com.zhangxin.threadcoreknowledge.threadobjectclasscommonmethods;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.LinkedList;

/**
 * 通过 wait 和 notify来实现生产者和消费者摸索
 */
public class Demo04ProducerConsumerModel {

    public static void main(String[] args) {
        EventStorage storage = new EventStorage();
        Producer producer = new Producer(storage);
        Consumer consumer = new Consumer(storage);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

    class Producer implements Runnable{

        private EventStorage storage;

        public Producer(EventStorage storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.put();
            }
        }
    }

    class Consumer implements Runnable{

        private EventStorage storage;

        public Consumer(EventStorage storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.take();
            }
        }
    }

    class EventStorage{

        private int maxSize;

        private LinkedList<Date> storage;

        public EventStorage() {
            this.maxSize = 10;
            storage = new LinkedList<>();
        }

        public synchronized void put() {
            while (storage.size() == maxSize) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            storage.add(new Date());
            System.out.println("仓库里有了" + storage.size() + "个产品");
            notify(); // 通知已经休眠的消费者.来进行消费
        }

        public synchronized void take() {
            while (storage.size() == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("拿到了" + storage.remove() + ", 现在仓库中还剩余 " + storage.size());
            notify();
        }

    }


